var noteTableUpdate;
var orderNoteindex = 0; // 表格行index
var nEditingNote = null;

var notelist = {};
notelist.operation = {};
notelist.bizKey = ""; // 缓存页面对应的业务主键

var $noteTable = null; // 缓存表格对象

$(function() {
    // 从URL上获取业务主键
    notelist.bizKey = extractParam("busiKey");
    if (!!notelist.bizKey) {
        notelist.operation.refreshNoteList();
    }
    // 新增便签的事件绑定
    $("#createNote").on("click", function() {
        var noteContent = $("#noteContent").val();
        if (!!noteContent) {
            notelist.operation.insertNote();
        } else {
            window.top.window.showScoMessage('error', "请录入便签内容");
        }
    });

    // 便签长度限制，最长80个字符（中英均是），40个字符时提示
    $("#noteContent").maxlength({
        alwaysShow : false,
        threshold : 40,
        warningClass : "label label-warning",
        limitReachedClass : "label label-danger",
        separator : ' / '
    });
});

notelist.operation.modifyNote = function(noteId, content) {
    var returnValue = false;
    $.ajax({
        type : "get",
        url : "/note/updateExistingNote.action",
        data : {
            "content" : encodeURI(content),
            "noteId" : noteId
        },
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        async : false, // 同步
        success : function(data) {
            if (data.result == "success") {
                returnValue = true;
                // 刷新表格
                //                notelist.operation.refreshNoteList();
            } else {
                window.top.window.showModalAlert(data.errormessage);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showScoMessage('error', result.errorObject.errorText);
            }
        }
    });
    return returnValue;
};

notelist.operation.insertNote = function(noteContent) {
    if (!noteContent) {
        noteContent = $("#noteContent").val();
    }
    if (!!noteContent) {
        $.ajax({
            type : "get",
            url : "/note/createNewNote.action",
            data : {
                "content" : encodeURI(noteContent),
                "busiKey" : notelist.bizKey
            },
            contentType : "application/json;charset=utf-8",
            dataType : "json",
            async : true, // 同步
            success : function(data) {

                if (data.result == "success") {
                    // 刷新表格
                    $("#noteContent").val("");
                    notelist.operation.refreshNoteList();
                } else {
                    window.top.window.showModalAlert(data.errormessage);
                }
            },
            error : function(XMLHttpRequest, textStatus) {
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    window.top.window.showScoMessage('error', result.errorObject.errorText);
                }
            }
        });
    } else {
        window.top.window.showScoMessage('error', "请输入便签内容");
    }
};

// 根据业务主键获取内部便签
notelist.operation.refreshNoteList = function() {
    if (!$noteTable) {
        $noteTable = $("#noteTable").DataTable({
            "processing" : true,
            "serverSide" : true,
            "dom" : '<"bottom"rtflp>',
            "searching" : false,
            "scrollY" : "140px",
            "scrollCollapse" : false,
            "destroy" : true,
            "paging" : false,
            "ordering" : false,
            "deferRender" : true,
            "ajax" : {
                "url" : "/note/getNoteList.action",
                "type" : "get",
                "data" : {
                    "busiKey" : notelist.bizKey
                }
            },
            "columns" : [ {
                "data" : "operation",
                "defaultContent" : "<a class='edit-btn' type='button'><i class='fa fa-edit'></i></a>"
            }, {
                "className" : "truncate-text tooltip-column-detail",
                "data" : "note"
            }, {
                "data" : "createTime"
            }, {
                "data" : "operUserName"
            }]
        }).on('draw.dt',function(){
            $("#noteTable").tooltip({
                selector : ".tooltip-column-detail",
                container : "body",
                title : function() {
                    if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                        return $(this).text();
                    }
                }
            });
});;
    } else {
        $noteTable.ajax.reload();
    }

    // 设置编辑按钮的功能
    var editableIndex = 1; // 第2列，即内容列可以编辑
    $("#noteTable tbody").on("click", ".edit-btn", function(event) {
        // 为了阻止冒泡，加的校验
        if ($(event.currentTarget).hasClass("edit-btn")) {
        var tds = $(this).parents("tr").children();
        $.each(tds, function(i, val) {
            var jqob = $(val);
            if (i != editableIndex || jqob.has('button').length) {
                return true;
            } else {
                var txt = jqob.text();
                var put = $("<input type='text' style='width:100%;' maxlength='80'>");
                put.maxlength({
                    alwaysShow : false,
                    threshold : 40,
                    warningClass : "label label-warning",
                    limitReachedClass : "label label-danger",
                    separator : ' / '
                });
                put.val(txt);
                jqob.html(put);
                return false;
            }
        });
        $(this).html("<i class='fa fa-save'>");
        $(this).toggleClass("edit-btn");
        $(this).toggleClass("save-btn");

    }    });
    // 设置保存按钮的功能——如果保存完成，就更新表格，如果保存失败，就给出提示并退出
    $("#noteTable tbody").on("click", ".save-btn", function(event) {
        // 为了阻止冒泡，加的校验
        if ($(event.currentTarget).hasClass("save-btn")) {
            var row = $noteTable.row($(this).parents("tr"));
            var rowData = row.data();
            var tds = $(this).parents("tr").children();
            $.each(tds, function(i, val) {
                var jqob = $(val);
                // 把input变为字符串
                if (!jqob.has('button').length) {
                    var txt = jqob.children("input").val();
                    if (!!txt) {

                        var returnValue = notelist.operation.modifyNote(rowData.noteId, txt);
                        if (returnValue) {
                            var index = $noteTable.cell(jqob).index().column;
                            var colName = $($noteTable.column(index).header()).attr("colvalue");
                            rowData[colName] = txt;
                            jqob.html(txt);
                        } else {
                            window.top.window.showScoMessage('error', "更新失败，请刷新后重试");
                        }
                    }
                }
            });
            row.data(rowData);

            $(this).html("<i class='fa fa-edit'></i>");
            $(this).toggleClass("edit-btn");
            $(this).toggleClass("save-btn");
        }
    });
};
// =============公共方法=============

// 解析某个URL中的参数的取值
function GetArgsFromHref(sHref, sArgName) {
    var args = sHref.split("?");
    var retval = "";

    if (args[0] == sHref) /* 参数为空 */
    {
        return retval; /* 无需做任何处理 */
    }
    var str = args[1];
    args = str.split("&");
    for (var i = 0; i < args.length; i++) {
        str = args[i];
        var arg = str.split("=");
        if (arg.length <= 1)
            continue;
        if (arg[0] == sArgName)
            retval = arg[1];
    }
    return retval;
}

// 从当前网页的URL中获取参数取值
function extractParam(paramName) {
    var returnString = "";
    var str = window.location.search;
    if (!!str) {
        returnString = GetArgsFromHref(str, paramName);
    }
    return returnString;
}